﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace Nirvana
{
    public sealed class LogFile : ILogAppender
    {
        private string logpath;
        private List<string> loglist = new List<string>();
        private float logtime;
        public LogFile(bool isAutoFlush)
        {
            string str = string.Empty;
            
            switch (Application.platform)
            {
                case RuntimePlatform.WindowsEditor:
                    str = Application.dataPath + "/..";
                    break;
                case RuntimePlatform.IPhonePlayer:
                    str = Application.persistentDataPath;
                    break;
                case RuntimePlatform.Android:
                    str = Application.persistentDataPath;
                    break;
                case RuntimePlatform.OSXEditor:
                    str = Application.dataPath + "/..";
                    break;
                case RuntimePlatform.WindowsPlayer:
                    str = Application.dataPath;
                    break;
            }
            string fullpath = Path.GetFullPath(str + "/Log");
            if (!Directory.Exists(fullpath))
            {
                Directory.CreateDirectory(fullpath);
            }

            logpath = fullpath + "/DiagnosisLog.txt";
            Scheduler.AddFrameListener(AddLog);

        }

        public LogFile(string path)
        {
            logpath = path;
        }

        private void AddLog()
        {
            if(Time.time >= logtime + 1f)
            {
                File.WriteAllLines(this.logpath, this.loglist.ToArray());
                this.logtime = Time.time;
            }
        }

        public void ClearLog()
        {
            File.WriteAllText(logpath, string.Empty);
        }

        public void AppendLog(LogItem item)
        {
            string msg = string.Format("[{0}][{1}][{2}]: {3}", item.Severity, item.ModuleName, item.RecordTime, item.Message);
            this.loglist.Add(msg);
        }
    }
}

